package com.example.test02;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.test02.adapter.RelativeAdapter;
import com.example.test02.adapter.UploadRecordAdapter;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MyFragment extends Fragment {

    private String[] relationships;
    private String[] realNames;
    private String[] phones;
    private String[] recordDates;
    private String[] recordTitles;
    private String[] recordStatus;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);

        ListView listView = view.findViewById(R.id.relativeListView);
        ListView uploadRecordListView = view.findViewById(R.id.upLoadListView);

        // 获取缓存的 userId
        Integer userId = getUserIdFromCache();
        String userName = getUserNameFromCache();
        String userPhone = getPhoneFromCache();

        TextView userPhoneTextView = view.findViewById(R.id.my_user_phone);
        TextView userNameTextView = view.findViewById(R.id.my_user_name);

        if (userPhoneTextView != null) {
            userPhoneTextView.setText(userPhone);
        }
        if (userNameTextView != null) {
            userNameTextView.setText(userName);
        }

        if (userId != null) {
            // 发送请求获取亲属信息
            getRelativesInfo(userId);
            // 发送请求获取上传记录信息
            getUploadRecordsInfo(userId);
        } else {
            // 用户未登录或 userId 未缓存
            Toast.makeText(getContext(), "用户未登录或 userId 未缓存", Toast.LENGTH_SHORT).show();
        }

        Log.d("MyFragment", "onCreateView called");
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.d("MyFragment", "onResume called");
    }

    private void getRelativesInfo(int userId) {
        OkHttpClient client = new OkHttpClient();
        String userIdString = String.valueOf(userId);

        Request request = new Request.Builder()
                .url("http://120.26.59.7:17321/api/relatives?userId=" + userIdString)
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "服务器返回错误: " + response.code(), Toast.LENGTH_SHORT).show();
                    });
                    return;
                }

                String responseData = response.body().string();
                try {
                    JSONObject jsonResponse = new JSONObject(responseData);
                    int code = jsonResponse.getInt("code");
                    String message = jsonResponse.getString("message");

                    if (code == 0) {
                        JSONArray data = jsonResponse.getJSONArray("data");

                        List<String> relationshipsList = new ArrayList<>();
                        List<String> realNamesList = new ArrayList<>();
                        List<String> phonesList = new ArrayList<>();

                        for (int i = 0; i < data.length(); i++) {
                            JSONObject relative = data.getJSONObject(i);
                            relationshipsList.add(relative.getString("relationship"));
                            realNamesList.add(relative.getString("realName"));
                            phonesList.add(relative.getString("phone"));
                        }

                        requireActivity().runOnUiThread(() -> {
                            // 更新 UI
                            relationships = relationshipsList.toArray(new String[0]);
                            realNames = realNamesList.toArray(new String[0]);
                            phones = phonesList.toArray(new String[0]);

                            ListView listView = getView().findViewById(R.id.relativeListView);
                            listView.setAdapter(new RelativeAdapter(getContext(), relationships, realNames, phones));
                        });
                    } else {
                        requireActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "获取亲属信息失败: " + message, Toast.LENGTH_SHORT).show();
                        });
                    }
                } catch (Exception e) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "解析响应数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }
    private void getUploadRecordsInfo(int userId) {
        OkHttpClient client = new OkHttpClient();
        String userIdString = String.valueOf(userId);

        Request request = new Request.Builder()
                .url("http://120.26.59.7:17321/api/video/records?userId=" + userIdString)
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "服务器返回错误: " + response.code(), Toast.LENGTH_SHORT).show();
                    });
                    return;
                }

                String responseData = response.body().string();
                try {
                    JSONObject jsonResponse = new JSONObject(responseData);
                    int code = jsonResponse.getInt("code");
                    String message = jsonResponse.getString("message");

                    if (code == 0) {
                        JSONArray data = jsonResponse.getJSONArray("data");

                        List<String> recordDatesList = new ArrayList<>();
                        List<String> recordTitlesList = new ArrayList<>();
                        List<String> recordStatusList = new ArrayList<>();

                        for (int i = 0; i < data.length(); i++) {
                            JSONObject record = data.getJSONObject(i);
                            recordDatesList.add(record.getString("uploadDate"));
                            recordTitlesList.add(record.getString("videoTitle"));
                            recordStatusList.add(record.getString("status"));
                        }

                        requireActivity().runOnUiThread(() -> {
                            // 更新 UI
                            recordDates = recordDatesList.toArray(new String[0]);
                            recordTitles = recordTitlesList.toArray(new String[0]);
                            recordStatus = recordStatusList.toArray(new String[0]);

                            ListView uploadRecordListView = getView().findViewById(R.id.upLoadListView);
                            uploadRecordListView.setAdapter(new UploadRecordAdapter(getContext(), recordDates, recordTitles, recordStatus));
                        });
                    } else {
                        requireActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "获取上传记录信息失败: " + message, Toast.LENGTH_SHORT).show();
                        });
                    }
                } catch (Exception e) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "解析响应数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }

    private int getUserIdFromCache() {
        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
        return sharedPreferences.getInt("userId", -1);
    }

    private String getUserNameFromCache() {
        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
        return sharedPreferences.getString("userName", "");
    }

    private String getPhoneFromCache() {
        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
        return sharedPreferences.getString("phone", "");
    }
}

